package br.com.fiaproupas.util;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.com.fiaproupas.model.Cliente;
import br.com.fiaproupas.model.Pedido;
import br.com.fiaproupas.model.Usuario;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

public class RetornaLista {
	
	private Gson gson;
	
	@SuppressWarnings("unchecked")
	public List<Pedido> buscaPedidos(String in){
		
	    Type listType = new TypeToken<ArrayList<Pedido>>() {}.getType();
		trataTimeStamp();
		
	    return (List<Pedido>) gson.fromJson(in, listType);		
	}
	
	@SuppressWarnings("unchecked")
	public List<Cliente> buscaClientes(String in){
		
	    Type listType = new TypeToken<ArrayList<Cliente>>() {}.getType();
		trataTimeStamp();
		
	    return (List<Cliente>) gson.fromJson(in, listType);		
	}
	
	@SuppressWarnings("unchecked")
	public List<Usuario> buscaUsuarios(String in){
		
	    Type listType = new TypeToken<ArrayList<Usuario>>() {}.getType();

	    return (List<Usuario>) new Gson().fromJson(in, listType);		
	}
	
	private void trataTimeStamp(){
	    GsonBuilder builder = new GsonBuilder();
	    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

			@Override
			public Date deserialize(JsonElement json, Type ofType,
					JsonDeserializationContext arg2) throws JsonParseException {
				return new Date(json.getAsJsonPrimitive().getAsLong());
			}
		});
	    
	    gson = builder.create();
	}
}
